<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Article extends Model
{

	use SoftDeletes;

	protected $table = 'article';
	/**
	 * 使用批量赋值的属性（白名单）
	 *
	 * @var array
	 */
	protected $fillable = [
		'title','category_id','author','thumb','content','is_show','sort'
	];

	public $timestamps = true;
	/**
	 * 不使用批量赋值的字段（黑名单）
	 *
	 * @var array
	 */
//	protected $guarded = ['*'];

	/**
	 * 一对一关联分类
	 * User: ihome
	 * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
	 */
	public function category()
	{
		return $this->belongsTo(Category::class,'category_id','id');
	}

	/**
	 * 多对多关联标签
	 * User: ihome
	 * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
	 */
	public function tag()
	{
		return $this->belongsToMany(Tag::class,'article_tag','article_id','tag_id');
	}


	//处理tag
	public function getTagIds(): Array
	{
		$tags = request()->input('tags');

		$tags = str_replace('，',',',$tags);

		$tags = explode(',',$tags);

		$ids = [];

		if($tags){
			foreach ($tags as $k => $v) {
			    $checkExist = Tag::query()->where(['tag_name'=>$v])->first();

			    if($checkExist){
			        $ids[] = $checkExist['id'];
			    }else{
			    	if($v){
						$ids[] = Tag::query()->insertGetId(['tag_name'=>$v]);
			    	}
				}
			}
		}

		return $ids;
	}

	/**
	 * 关联文章评论 一对多
	 * User: Clannad ~ ☆
	 * DateTime: 2019/11/2 09:33
	 * @return \Illuminate\Database\Eloquent\Relations\HasMany
	 */
	public function comment()
	{
		return $this->hasMany(Comment::class,'article_id','id');
	}
}
